import { login, queryUserInfo } from '@/api/login'
import { getToken, setToken, removeToken, setRefreshToken, getRefreshToken, setUserKey, removeUserKey, getUserKey } from '@/utils/auth'
import * as Utils from '@/utils/index'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    accountId: '',
    roleId: '',
    tenantId: '',
    userInfo: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ACCOUNTID: (state, id) => {
      state.accountId = id
    },
    SET_ROLE_ID: (state, id) => {
      state.roleId = id
    },
    SET_TENANT_ID: (state, id) => {
      state.tenantId = id
      sessionStorage.setItem('tenantId', id)
    },
    CLEAN_VISITED_VIEWS: (state, view) => {
      Utils.session('visitedViews', view)
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      // sessionStorage.setItem('userInfo', JSON.stringify(userInfo))
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('username', username)
        formData.append('password', userInfo.password)
        formData.append('grant_type', 'password')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        login(formData).then(response => {
          if (response.access_token) {
            setToken(response.access_token, response.expires_in)
            // setToken(response.access_token, 10)
            setUserKey(response.username, response.expires_in)
            // 设置刷新token
            setRefreshToken(response.refresh_token)
            commit('SET_TOKEN', response.access_token)
            commit('SET_ACCOUNTID', response.accountId)
            commit('SET_TENANT_ID', response.tenantId)
            resolve()
          } else {
            // 登录失败
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登录
    LoginServiceTicket({ commit }, serviceTicket) {
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('username', '')
        formData.append('password', '123456')
        formData.append('grant_type', 'password')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        formData.append('auth_type', '3PL')
        formData.append('serviceTicket', serviceTicket)
        login(formData).then(response => {
          if (response.access_token) {
            setToken(response.access_token, response.expires_in)
            // setToken(response.access_token, 10)
            setUserKey(response.username, response.expires_in)
            // 设置刷新token
            setRefreshToken(response.refresh_token)
            commit('SET_TOKEN', response.access_token)
            commit('SET_ACCOUNTID', response.accountId)
            commit('SET_TENANT_ID', response.tenantId)
            resolve()
          } else {
            // 登录失败
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录
    RefreshToken({ commit }) {
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('grant_type', 'refresh_token')
        formData.append('client_id', 'devops')
        formData.append('client_secret', 'devops')
        formData.append('refresh_token', getRefreshToken())
        login(formData).then(response => {
          if (response.access_token) {
            setToken(response.access_token, response.expires_in)
            // setToken(response.access_token, 10)
            setUserKey(response.username, response.expires_in)
            // 设置刷新token
            setRefreshToken(response.refresh_token)
            commit('SET_TOKEN', response.access_token)
            commit('SET_ACCOUNTID', response.accountId)
            commit('SET_TENANT_ID', response.tenantId)
            resolve()
          } else {
            // 刷新token失败
            setToken('')
            setRefreshToken('')
            commit('SET_TOKEN', '')
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        console.log('GetInfo()-state', state)
        queryUserInfo(getUserKey()).then(response => {
          commit('SET_USERINFO', response.data)
          commit('SET_ROLE_ID', response.data.roleId)
          // 本地数据
          const data = { roles: ['admin'], name: 'admin', avatar: 'http://img4.imgtn.bdimg.com/it/u=1506032837,1207917737&fm=200&gp=0.jpg' }
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch({})
      })
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        console.log('LogOut')
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_USERINFO', '')
        commit('CLEAN_VISITED_VIEWS', [{ name: '首页', path: '/dashboard', isclose: false }])
        removeToken()
        removeUserKey()
        resolve()
        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_ROLES', [])
        //   removeToken()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        console.log('FedLogOut')
        // sessionStorage.removeItem('userInfo')
        commit('SET_TOKEN', '')
        commit('SET_USERINFO', '')
        commit('CLEAN_VISITED_VIEWS', [{ name: '首页', path: '/dashboard', isclose: false }])
        removeToken()
        removeUserKey()
        resolve()
      })
    }
  }
}

export default user
